"use strict";
const through = require("through2");
const fs = require("fs");
const readline = require("readline");
module.exports = function (findArr) {
  return through.obj(function (file, enc, cb) {
    if (file.isNull()) {
      cb(null, file);
      return;
    }

    if (file.isStream()) {
      console.log("Streaming not supported");
      return;
    }

    if (!Array.isArray(findArr) || findArr.length < 1) {
      console.log("yllgulp-find-str-position配置中必须有待搜索的目标字符数组");
      return;
    }

    let func = (s) => {
      let res = {};
      findArr.map((item) => {
        res[item] = [];
        for (let i = 0; i < s.length; i++) {
          i = s.indexOf(item, i);
          if (i === -1) {
            break;
          } else {
            res[item].push(i);
          }
        }
        res[item].length < 1 ? delete res[item] : "";
      });
      return res;
    };

    let readRes = (str) => {
      fs.writeFile("exit_str.txt", str, { flag: "a+" }, function (err) {
        if (err) {
          throw err;
        }
      });
    };

    let validatenull = (val) => {
      if (typeof val == "boolean") {
        return false;
      }
      if (typeof val == "number") {
        return false;
      }
      if (val instanceof Array) {
        if (val.length == 0) return true;
      } else if (val instanceof Object) {
        if (JSON.stringify(val) === "{}") return true;
      } else {
        if (
          val == "null" ||
          val == null ||
          val == "undefined" ||
          val == undefined ||
          val == ""
        )
          return true;
        return false;
      }
      return false;
    };

    try {
      const lines = file.contents.toString().split(/\r?\n/);
      readRes(file.history.join(",") + "\n");
      lines.forEach((val, index) => {
        let getRes = func(val);
        if (!validatenull(getRes)) {
          readRes("line:" + index + "\t" + JSON.stringify(getRes) + "\n");
        }
      });
    } catch (err) {
      console.error(err);
    }
    cb(null, file);
  });
};
